#!/usr/bin/env python
# -*- coding: utf-8 -*-
# title       :
# author      : lee

import sys
import os
import logging
import re
from SceneCheckTool.checkScript.CheckBase import CheckBase

try:
    import maya.cmds as cmds
    import pymel.core as pm
    import jarryLibs.mayakit.MayaUtils as mu
    reload(mu)
except:
    pass

logging.basicConfig()
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)


class CfxPgYetiImportCheck(CheckBase):
    # 初始化检查属性表
    import_types_attr_lib = {0: "inputGeometry", 1: "inputStrandData", 2: "guideSets"}

    def __init__(self):
        super(CfxPgYetiImportCheck, self).__init__()

    def check_pgYeti_node_attrs(self):
        """
        描述：pgYeti节点检查的启动函数
        """
        error_nodes = []
        error_data = {}
        for yeti_node in cmds.ls(type="pgYetiMaya"):
            # 检查import节点属性是否正确
            import_check_result, error_nodes_data = self.check_pgYeti_import_attrs(yeti_node)
            if not import_check_result:
                error_nodes.append(yeti_node)
                error_data[yeti_node] = error_nodes_data
                continue

        return error_nodes, error_data

    def check_pgYeti_import_attrs(self, node):
        """
        描述：检查import节点中的type类型，并判断selection中的geometry对象是否存在，且是否与pgYeti节点中的Graph属性匹配
        """
        error_nodes = []
        check_key = True
        for graph_node in cmds.pgYetiGraph(node, listNodes=True):
            node_type = cmds.pgYetiGraph(node, node=graph_node, nodeType=True)
            if node_type == "import":
                geo_name = cmds.pgYetiGraph(node, node=graph_node, param="geometry", getParamValue=True)
                if not geo_name:
                    continue
                if not cmds.objExists(geo_name):
                    check_key = False
                    error_nodes.append(graph_node)
                    continue
                import_type_index = cmds.pgYetiGraph(node, node=graph_node, param="type", getParamValue=True)
                if import_type_index in self.import_types_attr_lib:
                    attr_name = self.import_types_attr_lib[import_type_index]
                    if not cmds.listConnections(node + "." + attr_name):
                        check_key = False
                        error_nodes.append(graph_node)
                        continue
                    input_shape_nodes = []
                    for connect_node in cmds.listConnections(node + "." + attr_name):
                        if cmds.listRelatives(connect_node, c=True, s=True):
                            for shape_node in cmds.listRelatives(connect_node, c=True, s=True):
                                input_shape_nodes.append(shape_node)
                        else:
                            input_shape_nodes.append(connect_node)
                    if geo_name not in input_shape_nodes and geo_name not in cmds.listConnections(node + "." + attr_name):
                        check_key = False
                        error_nodes.append(graph_node)
                        continue
                else:
                    print("Index {0} not in types_to_attrs lib, please check it.")
        return check_key, error_nodes

    def check_pgYeti_root_node(self, node):
        root_node = cmds.pgYetiGraph(node, getRootNode=True)
        if not root_node:
            return False
        if cmds.pgYetiGraph(node, node=root_node, outputNodeCount=True) > 0:
            return False
        return True

    def check(self):
        result_proc, error_nodes_data = self.check_pgYeti_node_attrs()
        if result_proc:
            error_nodes_message = u""
            for node in error_nodes_data:
                error_nodes_message += node + u"对应的Graph节点"
                for graph_node in error_nodes_data[node]:
                    error_nodes_message += graph_node + " "
                error_nodes_message += u"import节点不存在或输入节点与类型不匹配<br>"
            result_log = u'Error:报错节点为%s\n, 细节信息: %s\n' % (result_proc, error_nodes_message)
        else:
            result_log = u'Succeed:没有问题\n'

        return result_log

    def fix(self):
        pass
